<template>
  <div style="overflow: auto">
    <Breadcrumb menu="商品管理" submenu="添加商品" />

    <!-- card布局 -->
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeStepIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基础信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab是标签页 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeStepIndex"
          @tab-click="tabClick"
          :before-leave="tabBeforeLeave"
        >
          <el-tab-pane label="基础信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model.number="addForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="it.attr_name"
              v-for="it in manyTablData"
              :key="it.attr_id"
            >
              <el-checkbox-group v-model="it.attr_vals">
                <el-checkbox
                  border
                  :label="cb"
                  v-for="(cb, i) in it.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="it.attr_name"
              v-for="it in onlyTablData"
              :key="it.attr_id"
            >
              <el-input v-model="it.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="uploadHeaders"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="uploadSuccess"
              :on-error="uploadError"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button class="btnAdd" @click="addGoods" type="primary"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  name: "Add",
  data() {
    return {
      activeStepIndex: "0",
      //级联选择器配置对象
      cascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      cateList: [],
      //商品添加表单对象
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      //商品添加表单校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
      manyTablData: [],
      onlyTablData: [],
      //上传头部对象
      uploadHeaders: {
        Authorization: sessionStorage.getItem("token"),
      },
    };
  },
  methods: {
    handleChange() {
      if (this.addForm.goods_cat.length != 3) this.addForm.goods_cat = [];
    },
    //获取分类列表数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      this.cateList = res.data;
    },
    tabBeforeLeave(activeName) {
      if (this.addForm.goods_cat.length !== 3 && activeName !== "0") {
        this.$message.warning("请先选中商品分类");
        return false;
      }
      return true;
    },
    async getParamsList(param) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: param } }
      );
      if (param === "many") {
        res.data.forEach((el) => {
          el.attr_vals = el.attr_vals ? el.attr_vals.split(" ") : [];
        });
      }

      if (param === "many") {
        this.manyTablData = res.data;
      } else {
        this.onlyTablData = res.data;
      }
    },
    tabClick() {
      if (this.activeStepIndex === "1") {
        this.getParamsList("many");
      } else if (this.activeStepIndex === "2") {
        this.getParamsList("only");
      }
    },
    handleRemove(file) {
      const tempPath = file.response.data.tmp_path;
      const index = this.addForm.pics.findIndex((el) => el.pic === tempPath);
      this.addForm.pics.delete(index);
    },
    uploadSuccess(resp, file, fileList) {
      if (resp.meta.status !== 200) {
        this.$message.error("图片上传失败");
        fileList.remove(file);
        return;
      }
      this.addForm.pics.push({ pic: resp.data.tmp_path });
    },
    uploadError(err) {
      this.$message.error("图片上传失败");
    },
    addGoods() {
      this.$refs.addFormRef.validate( async(val) => {
        if (!val) {
          this.$message.error("请填写必要表单项");
          return;
        }
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");
        this.manyTablData.forEach((el) => {
          const info = {
            attr_id: el.attr_id,
            attr_value: el.attr_vals.join(" "),
          };
          form.attrs.push(info);
        });
        this.onlyTablData.forEach((el) => {
          const info = {
            attr_id: el.attr_id,
            attr_value: el.attr_vals,
          };
          form.attrs.push(info);
        });

        await this.$http.post('goods',form)
        this.$router.push('/goods')
      });
      // _.cloneDeep()
    },
  },
  computed: {
    cateId() {
      return this.addForm.goods_cat.last();
    },
  },
  created() {
    this.getCateList();
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-steps /deep/ .el-step__title {
  font-size: 13px;
}
.el-checkbox {
  margin: 0 15px 0 0 !important;
}

.btnAdd {
  margin-top: 15px;
}
</style>